package com.zeedev.flyingsaucer.beers.downloaders;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.zeedev.flyingsaucer.beers.activities.home.impl.HomeModel;
import com.zeedev.flyingsaucer.beers.activities.home.interfaces.HomeController;
import com.zeedev.flyingsaucer.global.UfoClubApp;
import com.zeedev.flyingsaucer.modules.DownloadModule.interfaces.DownloadManager;
import mobi.zeedev.flyingsaucer.common.CredentialsModule.impl.HomeInfo;
import mobi.zeedev.flyingsaucer.common.WebLinkModule.impl.UfoClubClientImpl;
import roboguice.util.Ln;
import roboguice.util.RoboAsyncTask;

/**
 * User: James Johnson
 * Date: Oct 29, 2010
 * Time: 8:30:24 PM
 */
public class LoginDownloader extends RoboAsyncTask {

    @Inject
    UfoClubApp app;

    @Inject
    Context mContext;

    @Inject
    Provider<HomeController> controller;

    @Inject
    DownloadManager downloadManager;

    @Inject
    UfoClubClientImpl beerLink;

    private static final String TAG = "LoginDownloader";

    private final HomeModel model;

    @Inject
    public LoginDownloader(HomeModel model) {
        this.model = model;
    }

    @Override
    public Object call() throws Exception {

        HomeInfo hm = null;

        hm = beerLink.getLoginMain();

        return hm;


    }

    @Override
    protected void onException(Exception e) throws RuntimeException {
        super.onException(e);
        Ln.w(e);
        Toast.makeText(mContext, "There was an error logging into the U.F.O. Club.", Toast.LENGTH_SHORT).show();
//        controller.get().viewLogin();
        //TODO fix?
    }

    @Override
    protected void onFinally() throws RuntimeException {
        super.onFinally();
        model.setRefreshing(false);
    }

    @Override
    protected void onPreExecute() throws Exception {
        super.onPreExecute();
        model.setRefreshing(true);
    }

    @Override
    protected void onSuccess(Object o) throws Exception {
        super.onSuccess(o);

        HomeInfo hm = (HomeInfo) o;

        if (TextUtils.isEmpty(hm.get(HomeInfo.E_MAIL))) {
//            Log.e(TAG, "Home Info: " + hm.toString());
            Toast.makeText(mContext, "Login failed, please check your credentials: E-Mail Address: " + hm.get(HomeInfo.E_MAIL), Toast.LENGTH_SHORT).show();
//            controller.get().viewLogin();
            return;
        }

        hm.didRefresh();
        model.setHomeInfo(hm);
//        Toast.makeText(mContext, "Your home screen has been refreshed.", Toast.LENGTH_SHORT).show();


    }
}
